package net

import (
	"fmt"
	"io"
	"net/http"
	"strconv"
	"strings"
)

type LocationData struct {
	Longitude float64
	Latitude  float64
	Code      string
	City      string
}
type IpUtil struct {
	Db2 *IpSearch
}

// https://www.qqzeng.com/
func (i IpUtil) NewQQZend() *IpUtil {
	search := GetInstance()
	return &IpUtil{
		Db2: search,
	}
}

func (i IpUtil) SearchQQZend(ip string) LocationData {
	record := i.Db2.Get(ip)
	split := strings.Split(record, "|")
	float1, _ := strconv.ParseFloat(split[9], 64)
	float2, _ := strconv.ParseFloat(split[10], 64)
	return LocationData{
		City:      split[2],
		Code:      split[8],
		Longitude: float1,
		Latitude:  float2,
	}
}

func (i IpUtil) GetLocalIp() string {
	responseClient, errClient := http.Get("https://icanhazip.com/") // 获取外网 IP
	if errClient != nil {
		fmt.Printf("获取外网 IP 失败，请检查网络\n")
		return ""
	}
	// 程序在使用完 response 后必须关闭 response 的主体。
	defer responseClient.Body.Close()
	body, _ := io.ReadAll(responseClient.Body)
	return fmt.Sprintf("%s", strings.Replace(string(body), "\n", "", -1))
}
